from django.conf import settings
from fdfs_client.client import get_tracker_conf, Fdfs_client
from rest_framework import status
from rest_framework.filters import SearchFilter
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from mg_admin.utils import PageNumPagination
from newsapp.models import Article,NewsCategory,ArticleImage
from mg_admin.serializers.article import ArticleSerializer,CategorySerializer,ArticleImageSerializer


class ArticleAPIView(ModelViewSet):
    pagination_class = PageNumPagination
    queryset = Article.objects.order_by('-id')
    serializer_class = ArticleSerializer
    filter_backends = [SearchFilter]  # 过滤字段
    search_fields = ['title','content']


class CategoryAPIView(ListAPIView):
    queryset = NewsCategory.objects.all()
    serializer_class = CategorySerializer


class ArticleImageAPIView(ModelViewSet):
    pagination_class = PageNumPagination
    queryset = ArticleImage.objects.order_by('-id')
    serializer_class = ArticleImageSerializer

    def create(self, request, *args, **kwargs):
        # 新增图片信息

        # 校验请求参数
        if all(request.data.values()):
            img_name = request.data.get('file').name

            # 手动上传图片
            tracker_path = get_tracker_conf(settings.FASTDFS_CONFIG_PATH)
            client = Fdfs_client(tracker_path)
            ret = client.upload_by_buffer(request.data['file'].read())

            # 判断是否上传成功
            if ret.get('Status') != 'Upload successed.':
                return Response(status=status.HTTP_403_FORBIDDEN)
            img_url = ret.get('Remote file_id').decode('utf-8')

            # 入库操作
            article_img = ArticleImage.objects.create(article_id=request.data.get('article'),image=img_url)

            # 返回响应
            return Response({
                'id':article_img.id,
                'article':article_img.article_id,
                'image':article_img.image.url,
                'filename':img_name,

            },status=status.HTTP_201_CREATED)
        else:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        
        
    def update(self, request, *args, **kwargs):
        # 校验请求参数
        if all(request.data.values()):
            img_name = request.data.get('file').name

            # 手动上传图片
            tracker_path = get_tracker_conf(settings.FASTDFS_CONFIG_PATH)
            client = Fdfs_client(tracker_path)
            ret = client.upload_by_buffer(request.data['file'].read())

            # 判断是否上传成功
            if ret.get('Status') != 'Upload successed.':
                return Response(status=status.HTTP_403_FORBIDDEN)
            img_url = ret.get('Remote file_id').decode('utf-8')

            # 修改操作
            article_img = self.get_object()
            article_img.article_id = request.data['article']
            article_img.image = img_url
            article_img.save()
            

            # 返回响应
            return Response({
                'id': article_img.id,
                'article': article_img.article_id,
                'image': article_img.image.url,
                'filename': img_name,

            }, status=status.HTTP_200_OK)
        else:
            return Response(status=status.HTTP_400_BAD_REQUEST)
